from rest_framework import serializers
from .models import Users, Addr, VerifyCode
from django.contrib.auth.password_validation import validate_password

# 验证序列化器

class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    password2 = serializers.CharField(write_only=True, required=True, validators=[validate_password])
    email = serializers.EmailField()
    class Meta:
        model = Users
        fields = ('username', 'password', 'password2', 'email', 'last_name')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError({"密码": "两次密码输入不一致"})
        if Users.objects.filter(email=attrs['email']).exists():
            raise serializers.ValidationError({"邮箱地址": "该邮箱已被其他账号绑定"})
        return attrs

    def create(self, validated_data):
        validated_data.pop('password2')  # 从验证后的数据中移除 password2 字段
        user = Users.objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            # first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],

        )

        user.set_password(validated_data['password'])
        user.save()

        return user
class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Users
        fields = ['id', 'username', 'email', 'phone_number', 'avatar', 'last_name']
class AddressSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(read_only=True, slug_field='username')
    class Meta:
        model = Addr
        fields = "__all__"
        read_only_fields = ['user']

class AvatarSerializer(serializers.ModelSerializer):
    avatar = serializers.ImageField()
    class Meta:
        model = Users
        fields = ['avatar']

class VerifySerializer(serializers.ModelSerializer):
    class Meta:
        model = VerifyCode
        fields = ['mobile', "code"]